package com.zker.missyou.sample.core;/*
 * ClassName: GlobalException
 * Package : com.zker.missyou.sample.core
 * Description:
 * @Author zKer
 * @Create 2024/6/27 13:22
 */

import com.zker.missyou.sample.core.configuration.ExceptionCodeConfiguration;
import com.zker.missyou.sample.exception.http.HttpException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;
import java.util.List;

@RestControllerAdvice
public class GlobalException {
    @Autowired
    private ExceptionCodeConfiguration exceptionCodeConfiguration;

    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public UnifyResponse HandleException(HttpServletRequest request, Exception e) {
        System.out.println("全局异常处理");
        UnifyResponse message = new UnifyResponse(10001, "服务器异常",
                request.getMethod() + " " + request.getRequestURI());
        return message;
    }

    @ExceptionHandler(HttpException.class)
    public ResponseEntity HandleHttpException(HttpServletRequest request, HttpException e) {
        System.out.println("Http异常处理");
        UnifyResponse message = new UnifyResponse(e.getCode(), exceptionCodeConfiguration.getMessage(e.getCode()),
                request.getMethod() + " " + request.getRequestURI());
        //设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        //设置响应码
        HttpStatus status = HttpStatus.resolve(e.getHttpStatusCode());
        //封装响应
        ResponseEntity<UnifyResponse> responseEntity = new ResponseEntity<>(message, headers, status);
        return responseEntity;
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public UnifyResponse HandleBeanValidationException(HttpServletRequest request,
                                                                       MethodArgumentNotValidException e) {
        String method = request.getMethod();
        String uri = request.getRequestURI();
        List <ObjectError> errors = e.getBindingResult().getAllErrors();
        String messages = this.formatAllErrorMessages(errors);
        return new UnifyResponse(10001, messages, method + " " + uri);
    }
    private String formatAllErrorMessages(List<ObjectError> errors){
        StringBuffer errorMsg = new StringBuffer();
        for (ObjectError error : errors) {
            errorMsg.append(error.getDefaultMessage()).append(";");
        }
        return errorMsg.toString();
    }

    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public UnifyResponse handleConstraintViolationException(HttpServletRequest request,
                                                                          ConstraintViolationException e) {
        String method = request.getMethod();
        String uri = request.getRequestURI();
//        for(ConstraintViolation error : e.getConstraintViolations()){
//            ConstraintViolation a = error;
//        }

        return new UnifyResponse(10001, e.getMessage(), method + " " + uri);
    }
}
